package com.bruce.download.core;

import com.bruce.download.constant.Constant;
import com.bruce.download.util.HttpUtils;
import com.bruce.download.util.LogUtils;

import java.io.BufferedInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.net.HttpURLConnection;
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;

/**
 * 分块下载
 * <br>CreateDate  2021/09/14 17:18:13
 *
 * @author luotuan
 * @version 1.0.0
 */
public class DownloaderTask implements Callable<Boolean> {
    private String url;

    /**
     * 下载的起始位置
     */
    private long startPos;

    /**
     * 下载的结束位置
     */
    private long endPos;

    /**
     * 标识当前是哪一部分
     */
    private int part;

    private CountDownLatch countDownLatch;

    public DownloaderTask(String url, long startPos, long endPos, int part, CountDownLatch countDownLatch) {
        this.url = url;
        this.startPos = startPos;
        this.endPos = endPos;
        this.part = part;
        this.countDownLatch = countDownLatch;
    }

    @Override
    public Boolean call() throws Exception {
        // 获取文件名
        String fileName = HttpUtils.getHttpFileName(url);
        fileName = fileName + ".temp" + part;
        //下载路径
        fileName = Constant.PATH + fileName;
        //获取分块下载的连接
        HttpURLConnection httpURLConnection = HttpUtils.getHttpURLConnection(url, startPos, endPos);
        try (
                InputStream in = httpURLConnection.getInputStream();
                BufferedInputStream bis = new BufferedInputStream(in);
                RandomAccessFile baf = new RandomAccessFile(fileName, "rw");
        ) {
            int len = -1;
            byte[] buffer = new byte[Constant.BYTE_SIZE];
            while ((len = bis.read(buffer)) != -1) {
                DownloadInfoThread.downSize.add(len);
                baf.write(buffer, 0, len);
            }
        } catch (FileNotFoundException e) {
            LogUtils.error("下载文件不存在{}", url);
            return false;
        } catch (Exception e) {
            LogUtils.error("下载出现异常");
            return false;
        } finally {
            httpURLConnection.disconnect();
            countDownLatch.countDown();
        }
        return true;
    }
}
